// miniprogram/pages/home_detail.js
import {
  db
} from "../../utils/index"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    type: "1",
    classifyDetail: {
      foods: []
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options, 'options');
    this.getData(options.type);
    this.setData({
      type:options.type
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },
  // 获取菜谱数据
  getData(type = 1) {
    console.log(type,'type');
    wx.cloud.callFunction({
      name: "getHomeDetail",
      data: {
        type:String(type)
      }
    }).then(res => {
      // console.log(res, 'rrrrr');
      let classify = res.result.result;
      let edit = res.result.edit;
      console.log(res.result);
      if (classify) {

        wx.cloud.callFunction({
          name: "checkLike",
          data: {
            classifyId: classify._id
          }
        }).then(res => {
          let likes = res.result.data;
          classify.foods = classify.foods.map(el => {
            let aim = likes.find(ev => ev.cp.id === el.id);
            el.like = Boolean(aim);
            return el;
          })
          wx.hideLoading();
          this.setData({
            classifyDetail: classify,
            edit:edit
          })
        });
      }
    })
  },
  // 添加喜欢
  handleLike(event) {

    // console.log(this.data.classifyDetail._id);
    let cp = event.target.dataset.item;
    const likeStatus = cp.like;
    let name = likeStatus ? "cancelLike" : "addLike";
    wx.showLoading({
      mask: true
    });
    wx.cloud.callFunction({
      name: name,
      data: {
        cp,
        classifyId: this.data.classifyDetail._id
      }
    }).then(res => {
      console.log(cp, this.data.classifyDetail._id);
      if (res.result.code === 200) {

      }
      console.log(res.result,this.data.type)
      this.getData(this.data.type);
      wx.showToast({
        title: res.result.msg,
      });
    })
  },
  // 删除个人创建的菜谱
  deletClassify(){
    let classify = this.data.classifyDetail;
    console.log(classify._id);
    wx.showLoading({
      mask:true
    })
    wx.cloud.callFunction({
      name:"deleteHomeDetail",
      data:{
        type:classify.type,
        classifyId:classify._id
      }
    }).then(res=>{
      wx.switchTab({
        url: '/pages/home/home',
      });
      wx.showToast({
        title: res.result.msg,
      })
    })
  },
  toDetail(event){
    wx.navigateTo({
      url: '/pages/cpcontent/index',
    })
  }
})